package cn.yangliu.task.utils;

import cn.yangliu.task.TaskFactoryBean;
import cn.yangliu.task.entity.Task;
import cn.yangliu.task.service.TaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ScheduledFuture;

public class TaskUtils {

    private static final Logger logger = LoggerFactory.getLogger(TaskFactoryBean.class);


    /**
     * 检查定时任务执行次数
     *
     * @param task
     * @return
     */
    public static boolean checkExcuteCount(Task task) {

        //没有设置计划任务执行次数
        if (task.getExcuteTotalCount() == null || task.getExcuteTotalCount() <= 0) {
            logger.debug("定时任务未设置计划执行次数");
            return true;
        }

        //计划任务执行次数大于已执行次数
        if (task.getExcuteTotalCount() > task.getExcuteCount()) {
            logger.debug("计划任务执行次数大于已执行次数");
            int excuteCount = task.getExcuteCount();
            excuteCount++;
            task.setExcuteCount(excuteCount);
            return true;
        }
        //停止任务
        ScheduledFuture<?> future= TaskFactoryBean.getScheduledFuture(task.getId());
        future.cancel(true);

        return false;
    }


}
